<template>
	<div class="upload">
		<div class="oss_file">
			<input type="file" :id="id" @change="doUpload" />
			<img :src="url" alt="">
		</div>
	</div>
</template>

<script>
	import http from '@/assets/js/http.js'
//	import OSS from 'oss'
	
	export default {
		name: 'upload',
		data() {
			return {
				region: 'oss-cn-shanghai',
				//根据你买的那个区的做相应的更改
				bucket: 'fengzhan',
				id: 'upload',
				percentage: 0,
				url: '',
				urls: [],
				getToken: {
					sign: '',
				}
			}
		},
		methods: {
			doUpload() {
				const _this = this;
				const urls = [];
				_this.apiGet('/api/help/oss/sts').then((result) => {
					console.log(result);
					const client = new OSS.Wrapper({
						region: _this.region,
						bucket: _this.bucket,
						accessKeyId: result.data.accessKeyId,
						accessKeySecret: result.data.accessKeySecret,
						stsToken: result.data.SecurityToken,
					})
					_this.percentage = 0;
					const files = document.getElementById(_this.id)
					console.log('files', files)
					if(files.files) {
						const fileLen = document.getElementById(_this.id).files
						let resultUpload = ''
						for(let i = 0; i < fileLen.length; i++) {
							const file = fileLen[i]
							// 随机命名
							let random_name = this.random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop()
							// 上传
							client.multipartUpload(random_name, file, {
								progress: function*(percentage, cpt) {
									// 上传进度
									_this.percentage = percentage
								}
							}).then((results) => {
								// 上传完成
								const url = 'http://fengzhan.oss-cn-shanghai.aliyuncs.com/' + results.name;
//								_this.$store.dispatch("changeUrl", _this.url);
								_this.url = url;
								console.log(url);
							}).catch((err) => {
								console.log(err)
							})
						}
					}
				})
			},

			// 随机生成文件名  
			random_string(len) {　　
				len = len || 32;　　
				var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
				var maxPos = chars.length;　　
				var pwd = '';　　
				for(let i = 0; i < len; i++) {　　
					pwd += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			}
		},
		watch: {
			url(val) {
				if(val) {
					this.urls.push(val);
				}
			}
		},
		mixins: [http]
		
	}
</script>

<!--<style lang="less">
		.oss_file {
		height: 150px;
		width: 150px;
		border-radius: 50%; 
		background: red; img{ width:100%; display: inline-block; float: right; } } .oss_file input { right: 0; top: 0; opacity: 0; filter: alpha(opacity=0); cursor: pointer; width: 100%; height: 100%; }
</style>-->